package com.ruoyi.framework.security.provider;

// 自定义AuthenticationProvider
import com.ruoyi.framework.security.token.NoPwdAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    public CustomAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object principal = authentication.getPrincipal();
//        Object details = authentication.getDetails();
//        Object credentials = authentication.getCredentials();

        UserDetails userDetails = userDetailsService.loadUserByUsername(principal.toString());
        if (userDetails != null && ifLoginWithOutPwd(authentication)) {
            return new NoPwdAuthenticationToken(userDetails, null);
        }

        // 否则，继续使用正常的密码验证逻辑
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return NoPwdAuthenticationToken.class.isAssignableFrom(authentication);
    }

    private boolean ifLoginWithOutPwd(Authentication authentication) {
        // 在这里添加判断用户是否符合免密登录条件的逻辑，例如检查用户的角色等
        if(authentication instanceof NoPwdAuthenticationToken) {
            return true;
        }
        return false;
    }
}
